package com.reiuy.controller;



import com.reiuy.entity.Cart;
import com.reiuy.vo.Cartinfo;
import com.reiuy.entity.Good;
import com.reiuy.entity.User;
import com.reiuy.service.CartService;
import com.reiuy.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
@RequestMapping("/cart")
public class CartController {
    @Resource
    private CartService cartService;


    @RequestMapping( value = "/addgoodintocart.do",produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String addgoodintocart(User user, Good good, HttpServletRequest request){
        String msg = "";

        int nums = cartService.addcart(user,good,1);
        if(nums > 0){
            msg = "添加成功";
        }else if(nums == -2){
            msg = "不能将自己的商品加入购物车";
        }
        else{
            msg = "添加失败";
        }
        return msg;
    }

    @RequestMapping("/foundcart.do")
    public ModelAndView foundcart(HttpServletRequest request){
        ModelAndView mv = new ModelAndView();
        User user = new User();
        user.setUsername((String) request.getSession().getAttribute("username"));

        List<Cartinfo> carts = cartService.foundusercart(user);
        System.out.println(carts);
        if(carts == null){
            //TODO 如果购物车为空,则应该返回购物车为空的页面
        }else {
            mv.addObject("carts",carts);
            mv.setViewName("cart/cartinfo");
        }
        return mv;
    }


    @RequestMapping(value = "/deletecart.do",produces = "text/plain;charset=utf-8")
    @ResponseBody
    public String deletecart(Cart cart){
        String msg = "";
        int nums = cartService.deletecart(cart);
        if(nums > 0){
            msg = "删除成功,已将该商品移除购物车";
        }else{
            msg = "删除失败";
        }
        return msg;
    }
}
